package com.Policing.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Since_case.Since_case;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.demo.WaveSwipeRefreshLayout;
import com.Policing.Adapter.Public_list_item_Adapter;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.Repairs.Add_Repairs;
import com.Policing.Repairs.Repairs_property;
import com.Policing.bean.Repairs_bean;
import com.Policing.menu.SlideSideMenuExampleActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.*;

/**
 * Created by Administrator on 2019/3/13.
 */

public class Repairs extends Fragment {
    private ImageView imageView,add,screen;
    private ListView lv_list;
    public Context context;
    private String id;
    private TextView title_text;
    List<Map<String, Object>> order = new ArrayList<Map<String, Object>>();
    List<Map<String, Object>> maintenanceing = new ArrayList<Map<String, Object>>();
    private SlideSideMenuExampleActivity mainActivity;
    WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private String url="http://"+ Ip_Set.IP+"/api/repairsQuery";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.repairs, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        SharedPreferences mm = getActivity().getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id","");
        mainActivity = (SlideSideMenuExampleActivity) getActivity();
        inview();

        lv_list.setOnItemClickListener((parent, view, position, id) -> {
            String str = String.valueOf(lv_list.getAdapter().getItem(position));
            String[] strs=str.split(",");
            Intent intent = new Intent(mainActivity, Repairs_property.class);
            intent.putExtra("repairsId", strs[1].toString());
            intent.putExtra("state",strs[2].toString());
            startActivity(intent);
        });
    }

    private void inview() {
        title_text = (TextView) mainActivity.findViewById(R.id.title_text);
        title_text.setText("报修");
        screen = (ImageView) mainActivity.findViewById(R.id.screen);
        screen.setOnClickListener(v -> new AlertView("筛选", null, "取消", new String[]{"全部"}, new String[]{"申请中", "已审核"}, mainActivity, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position==0){
                    //适配器，刚刚重写的！
                    Public_list_item_Adapter re_ad = new Public_list_item_Adapter(mainActivity,list);
                    lv_list.setAdapter(re_ad);
                }
                if (position==2){
                    maintenanceing.clear();
                    for (int i = 0;i<list.size();i++){
                        if (list.get(i).get("scope").equals("已审核")){
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd_tv","报修单号");
                            map.put("creator_tv","数量");
                            map.put("sum_tv","报修部门");
                            map.put("state_tv","创建人");
                            map.put("scope_tv","状态");
                            map.put("Date_created_tv","创建日期");
                            map.put("Inventory_date_tv","");

                            map.put("scope",list.get(i).get("scope"));
                            map.put("state",list.get(i).get("state"));
                            map.put("odd",list.get(i).get("odd"));
                            map.put("Date_created",list.get(i).get("Date_created"));
                            map.put("creator",list.get(i).get("creator"));
                            map.put("sum",list.get(i).get("sum"));
                            map.put("Inventory_date",list.get(i).get("Inventory_date"));
                            maintenanceing.add(map);
                        }
                    }
                    Public_list_item_Adapter re_ad = new Public_list_item_Adapter(mainActivity,maintenanceing);
                    lv_list.setAdapter(re_ad);

                }
                if (position==1){
                    order.clear();
                    for (int i = 0;i<list.size();i++){
                        if (list.get(i).get("scope").equals("申请中")){

                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd_tv","报修单号");
                            map.put("creator_tv","数量");
                            map.put("sum_tv","报修部门");
                            map.put("state_tv","创建人");
                            map.put("scope_tv","状态");
                            map.put("Date_created_tv","创建日期");
                            map.put("Inventory_date_tv","");

                            map.put("scope",list.get(i).get("scope"));
                            map.put("state",list.get(i).get("state"));
                            map.put("odd",list.get(i).get("odd"));
                            map.put("Date_created",list.get(i).get("Date_created"));
                            map.put("creator",list.get(i).get("creator"));
                            map.put("sum",list.get(i).get("sum"));
                            map.put("Inventory_date",list.get(i).get("Inventory_date"));
                            order.add(map);
                        }
                    }
                    Public_list_item_Adapter re_ad = new Public_list_item_Adapter(mainActivity,order);
                    lv_list.setAdapter(re_ad);

                }


            }
        }).show());
        add = (ImageView) mainActivity.findViewById(R.id.add);
        add.setOnClickListener(v -> {
            Intent intent = new Intent(mainActivity, Add_Repairs.class);
            startActivity(intent);
        });
        lv_list = (ListView) getActivity().findViewById(R.id.check_list);
        imageView = (ImageView) getActivity().findViewById(R.id.opmenu);
        imageView.setOnClickListener(v -> {
            SlideSideMenuTransitionLayout mSlideSideMenu= (SlideSideMenuTransitionLayout)getActivity().findViewById(R.id.slide_side_menu);
            mSlideSideMenu.toggle();
        });
        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) getActivity().findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                //模拟3秒的加载过程
                new Handler().postDelayed(() -> {
                    load();
                    //接下来可以刷新ListView
                }, 1200);


            }

        });
    }

    private void load() {
        new Thread(){
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("id",id)
                            .add("source", Since_case.set().getSource())
                            .build();
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.i("123123",responseData);
                    showResponse(responseData);

                } catch (IOException e) {
                    e.printStackTrace();

                }


            }
        }.start();
    }

    private void showResponse(final String responseData) {
        mainActivity.runOnUiThread(() -> {
            if (responseData.equals("[]")){
                Toast.makeText(mainActivity,"无报修单",Toast.LENGTH_SHORT).show();
            }
            list.clear();
            mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
            Gson gson = new Gson();
            List<Repairs_bean> userList = gson.fromJson(responseData, new TypeToken<List<Repairs_bean>>(){}.getType());
            for(int i = 0;i < userList.size();i++){
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("odd_tv","报修单号");
                map.put("creator_tv","数量");
                map.put("sum_tv","报修部门");
                map.put("state_tv","创建人");
                map.put("scope_tv","状态");
                map.put("Date_created_tv","创建日期");
                map.put("Inventory_date_tv","");


                map.put("odd",userList.get(i).getRepairsId());
                map.put("Date_created",userList.get(i).getCreatedate().substring(0,10));
                map.put("creator",userList.get(i).getSum());
                map.put("sum",userList.get(i).getDeptId());
                map.put("Inventory_date","");

                String zt ="";
                if (userList.get(i).getStatus().equals("1")){
                    zt="申请中";
                }
                if (userList.get(i).getStatus().equals("2")){
                    zt="已审核";
                }
                if (userList.get(i).getStatus().equals("3")){
                    zt="已维修";
                }
                if (userList.get(i).getStatus().equals("0")){
                    zt="驳回";
                }

                map.put("scope",zt);
                map.put("state",userList.get(i).getOperator());
                list.add(map);
                Collections.reverse(list);
            }
            Public_list_item_Adapter re_ad = new Public_list_item_Adapter(mainActivity,list);
            lv_list.setAdapter(re_ad);
        });
    }

    @Override
    public void onStart() {
        Timer timer=new Timer();//实例化Timer类
        timer.schedule(new TimerTask(){
            public void run(){
                load();
                this.cancel();
            }
        },500);//五百毫秒

        super.onStart();
    }
}
